/**
 * May 5, 2014 5:00:11 PM
 */
package elitech.vietnam.copyweatherfashion.fragments.settings;

import java.io.IOException;

import org.xmlpull.v1.XmlPullParserException;

import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.google.gson.Gson;

import elitech.vietnam.copyweatherfashion.LoginActivity;
import elitech.vietnam.copyweatherfashion.MainActivity;
import elitech.vietnam.copyweatherfashion.R;
import elitech.vietnam.copyweatherfashion.badge.BadgeHelper;
import elitech.vietnam.copyweatherfashion.dialog.ConfirmDialogFragment;
import elitech.vietnam.copyweatherfashion.dialog.ConfirmDialogFragment.ConfirmDialogClick;
import elitech.vietnam.copyweatherfashion.dialog.ConfirmDialogFragment.Type;
import elitech.vietnam.copyweatherfashion.dialog.ProgressDialogFragment;
import elitech.vietnam.copyweatherfashion.gcm.GCMIntentService;
import elitech.vietnam.copyweatherfashion.prefs.PrefsDefinition;
import elitech.vietnam.copyweatherfashion.utilities.MyCallable;
import elitech.vietnam.copyweatherfashion.wsclient.Service;

/**
 * @author Cong
 */
public class SettingsFragment extends Fragment implements View.OnClickListener, OnCheckedChangeListener, ConfirmDialogClick {

	MainActivity	mActivity;

	TextView		mBtnEdit, mBtnFriend, mBtnNotification, mBtnHelp, mTxtVersion, mBtnPass, mTxtLanguage;
	LinearLayout	mBtnLocation, mBtnLanguage;
	Button			mBtnLogin, mBtnLogout;
	ToggleButton	mToggleLocation;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mActivity = (MainActivity) getActivity();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.settings, container, false);

		mBtnEdit = (TextView) view.findViewById(R.id.setting_btnEditProfile);
		mBtnFriend = (TextView) view.findViewById(R.id.setting_btnFriendList);
		mBtnLocation = (LinearLayout) view.findViewById(R.id.setting_btnGetLocation);
		mToggleLocation = (ToggleButton) view.findViewById(R.id.setting_tggLocation);
		mBtnNotification = (TextView) view.findViewById(R.id.setting_btnNotification);
		mBtnHelp = (TextView) view.findViewById(R.id.setting_btnHelp);
		mTxtVersion = (TextView) view.findViewById(R.id.setting_txtVersion);
		mBtnPass = (TextView) view.findViewById(R.id.setting_btnChangePass);
		mTxtLanguage = (TextView) view.findViewById(R.id.setting_txtLanguage);
		mBtnLanguage = (LinearLayout) view.findViewById(R.id.setting_btnLanguage);
		mBtnLogin = (Button) view.findViewById(R.id.setting_btnLogin);
		mBtnLogout = (Button) view.findViewById(R.id.setting_btnLogout);

		mBtnEdit.setOnClickListener(this);
		mBtnFriend.setOnClickListener(this);
		mBtnLocation.setOnClickListener(this);
		mBtnNotification.setOnClickListener(this);
		mBtnHelp.setOnClickListener(this);
		mBtnPass.setOnClickListener(this);
		mBtnLanguage.setOnClickListener(this);
		mBtnLogin.setOnClickListener(this);
		mBtnLogout.setOnClickListener(this);
		mToggleLocation.setOnCheckedChangeListener(this);

		return view;
	}

	@Override
	public void onStart() {
		super.onStart();
		/*
		 * Initialize header view
		 */
		mActivity.mTxtTitle.setText(Html.fromHtml(getString(R.string.settings)));
		mActivity.mBtnBack.setVisibility(View.GONE);
		mActivity.mBtnCamera.setVisibility(View.GONE);
		mActivity.mBtnEdit.setVisibility(View.GONE);
		mActivity.mBtnNotify.setVisibility((mActivity.mUser!=null) ? View.VISIBLE : View.GONE);
		
		mToggleLocation.setChecked(mActivity.mOptions.mLocation);
		mTxtVersion.setText(mActivity.mConfig.getVersionName());
		mTxtLanguage.setText(mActivity.getLanguageName());

		if (mActivity.mUser != null) {
			mBtnLogin.setVisibility(View.GONE);
			mBtnLogout.setVisibility(View.VISIBLE);
		}
	}
	
	@Override
	public void onResume() {
		super.onResume();
		/**
		 * Implement onActivityResult Based on MainActivity.mRequestCode and
		 * MainActivity.mResultIntent
		 */
		if (mActivity.mRequestCode == MainActivity.REQUEST_LOGIN && mActivity.mResultIntent != null) {
			mActivity.getLoggedMemberInfo(mActivity.mResultIntent.getIntExtra(LoginActivity.EXTRA_USERID, -1),
					new MyCallable() {
						@Override
						public void call() {
							mBtnLogin.setVisibility(View.GONE);
							mBtnLogout.setVisibility(View.VISIBLE);
							mActivity.mBtnNotify.setVisibility(View.VISIBLE);
							mActivity.mRequestCode = -1;
							mActivity.mResultIntent = null;
						}
					});
		}
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		switch (buttonView.getId()) {
		case R.id.setting_tggLocation:
			mActivity.mOptions.mLocation = isChecked;
			mActivity.mPrefs.edit().putString(PrefsDefinition.OPTION, new Gson().toJson(mActivity.mOptions)).commit();
			break;
		default:
			break;
		}
	}

	@Override
	public void yesClick() {
		new LogoutTask().execute();
	}

	@Override
	public void noClick() {
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.setting_btnLogin:
			Intent intent = new Intent(mActivity, LoginActivity.class);
			mActivity.startActivityForResult(intent, MainActivity.REQUEST_LOGIN);
			break;
		case R.id.setting_btnLogout:
			new ConfirmDialogFragment.Builder()
			.setMessage(getString(R.string.logout_confirm_mess))
			.setTargetFragment(this)
			.setType(Type.FRAGMENT).build().show(getFragmentManager());
			break;
		case R.id.setting_btnFriendList:
			if (mActivity.mUser == null) {
				Intent i = new Intent(mActivity, LoginActivity.class);
				mActivity.startActivityForResult(i, MainActivity.REQUEST_LOGIN);
			} else {
				mActivity.getBase(MainActivity.TAB_SETTINGS).replaceFragment(new FriendListFragment(), true);
			}
			break;
		case R.id.setting_btnEditProfile:
			if (mActivity.mUser == null) {
				Intent i = new Intent(mActivity, LoginActivity.class);
				mActivity.startActivityForResult(i, MainActivity.REQUEST_LOGIN);
			} else {
				mActivity.getBase(MainActivity.TAB_SETTINGS).replaceFragment(new EditProfileFragment(), true);
			}
			break;
		case R.id.setting_btnGetLocation:
			mToggleLocation.performClick();
			break;
		case R.id.setting_btnNotification:
			mActivity.getBase(MainActivity.TAB_SETTINGS).replaceFragment(new NotificationsFragment(), true);
			break;
		case R.id.setting_btnHelp:

			break;
		case R.id.setting_btnChangePass:
			if (mActivity.mUser == null) {
				Intent i = new Intent(mActivity, LoginActivity.class);
				mActivity.startActivityForResult(i, MainActivity.REQUEST_LOGIN);
			} else {
				mActivity.getBase(MainActivity.TAB_SETTINGS).replaceFragment(new ChangePasswordFragment(), true);
			}
			break;
		case R.id.setting_btnLanguage:
			mActivity.getBase(MainActivity.TAB_SETTINGS).replaceFragment(new LanguageFragment(), true);
			break;
		default:
			break;
		}
	}

	
	class LogoutTask extends AsyncTask<Integer, Integer, Boolean> {
		ProgressDialogFragment	mProgress;

		@Override
		protected void onPreExecute() {
			mProgress = new ProgressDialogFragment.Builder().setTitle(getString(R.string.loading))
					.setMessage(getString(R.string.please_wait)).build();
			mProgress.show(getFragmentManager());
		}

		@Override
		protected Boolean doInBackground(Integer... params) {
			try {
				return new Service().updateGCM(mActivity.mUser.Id, "") > 0;
			} catch (IOException | XmlPullParserException e) {
				e.printStackTrace();
				return false;
			}
		}

		@Override
		protected void onPostExecute(Boolean result) {
			mProgress.dismiss();
			if (result) {
				mActivity.mUser = null;
				mActivity.mListNotify.clear();
				mBtnLogin.setVisibility(View.VISIBLE);
				mBtnLogout.setVisibility(View.GONE);
				mActivity.mBadgeCount = 0;
				mActivity.notifyBadgeChanged();
				BadgeHelper.updateBadge(mActivity, 0);
				NotificationManager manager = (NotificationManager) mActivity.getSystemService(Context.NOTIFICATION_SERVICE);
				manager.cancel(GCMIntentService.NOTIFICATION_ID);
				mActivity.mPrefs.edit().putString(PrefsDefinition.USER, "").commit();
				mActivity.mBtnNotify.setVisibility(View.GONE);
				Toast.makeText(mActivity, R.string.logoutsuccessful, Toast.LENGTH_SHORT).show();
			} else
				Toast.makeText(mActivity, R.string.cannot_connect_to_server, Toast.LENGTH_SHORT).show();
		}
	}
}
